package com.agranee.entity;

import javax.servlet.http.*;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.*;

@ManagedBean
@RequestScoped
public class RememberMeLogin {
	boolean remember;
	String username;
	String password;
	String remember1 = "hi";

	public RememberMeLogin() {
		checkCookie();
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getUsername() {
		if (remember == false) {
			username = "";
			return username;
		} else {
			return username;
		}
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		if (remember == false) {
			password = "";
			return password;
		} else {
			return password;
		}
	}

	public void setRemember(boolean remember) {
		this.remember = remember;
	}

	public boolean getRemember() {
		return remember;
	}

	public String CheckLogin() {
		if (username.equals("chandan") && password.equals("chandan")) {
			FacesContext facesContext = FacesContext.getCurrentInstance();

			// Save the userid and password in a cookie
			Cookie btuser = new Cookie("btuser", username);
			Cookie btpasswd = new Cookie("btpasswd", password);
			if (remember == false) {
				remember1 = "false";
			} else {
				remember1 = "true";
			}
			Cookie btremember = new Cookie("btremember", remember1);
			btuser.setMaxAge(3600);
			btpasswd.setMaxAge(3600);

			((HttpServletResponse) facesContext.getExternalContext()
					.getResponse()).addCookie(btuser);
			((HttpServletResponse) facesContext.getExternalContext()
					.getResponse()).addCookie(btpasswd);
			((HttpServletResponse) facesContext.getExternalContext()
					.getResponse()).addCookie(btremember);
			

			return "success";
		} else {
			return "failure";
		}
	}
	public void checkCookie() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		String cookieName = null;
		Cookie cookie[] = ((HttpServletRequest) facesContext
				.getExternalContext().getRequest()).getCookies();
		if (cookie != null && cookie.length > 0) {
			for (int i = 0; i < cookie.length; i++) {
				cookieName = cookie[i].getName();
				if (cookieName.equals("btuser")) {
					username = cookie[i].getValue();
				} else if (cookieName.equals("btpasswd")) {
					password = cookie[i].getValue();
				} else if (cookieName.equals("btremember")) {
					remember1 = cookie[i].getValue();
					if (remember1.equals("false")) {
						remember = false;
					} else if (remember1.equals("true")) {
						remember = true;
					}
				}
			}
		} else
			System.out.println("Cannot find any Cookie");
	}
}